<template>
    <SearchForm v-if="config.search" @callbackSearch="getList" />
    <el-button-group style="float:right;margin-bottom: 5px;">
        <el-button v-if="config.batch_delete" type="info" v-show="multipleSelection.length > 0"
            @click="handlerDelete('batch')">批量删除</el-button>
        <el-button v-if="config.creatProject" type="success" @click="addInfo">添加
            <el-icon class="el-icon--right">
                <ArrowRight />
            </el-icon>
        </el-button>
    </el-button-group>
    <el-table :row-key="getRowKeys" :default-expand-all="config.expand_all" :data="table_data.data"
        v-loading="table_data.loading" element-loading-text="加载中，请稍候" border style="width: 100%;"
        :header-cell-style="{ background: 'lightcyan', 'text-align': 'center' }" @selection-change="handleSelectionChange"
        :max-height="tableHeight" stripe @expand-change="expandColumn" :expand-row-keys="expands">
        <el-table-column v-if="config.selection" type="selection" width="40"></el-table-column>
        <el-table-column v-if="config.expand" type="expand">
            <template #default="props">
                <div class="table-detail">
                    <div style="margin: 10px;">
                        <p>
                        <p style="font-weight: bold;padding-top: 5px;">详情：</p>
                        <p>
                            {{ props.row.description }}
                        </p>
                        </p>
                    </div>
                </div>
            </template>
        </el-table-column>
        <template v-for="header in data.render_header" :key="header.prop" style="background-color: lightcyan;">
            <el-table-column v-if="header.type === 'slot'" :label="header.label" :width="header.width">
                <template #default="scope">
                    <slot :name="header.slot_name" :data="scope.row"></slot>
                    <el-tooltip content="删除" placement="bottom" effect="light">
                        <el-button v-if="header.delete_elem" type="danger" icon="Delete" circle
                            @click="handlerDelete('delete', scope.row)" />
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column v-else :prop="header.prop" :label="header.label" :width="header.width"></el-table-column>
        </template>

    </el-table>
    <div class="margin-top-20">
        <div style="float:right">
            <Pagination v-if="config.pagination" :total="table_data.total" :totalData="table_data.pagedata"
                @sizeChange="getTableList" @currentChange="getTableList" />
        </div>
    </div>
</template>

<script>
import { ArrowRight } from '@element-plus/icons-vue'
import { reactive, getCurrentInstance, onBeforeMount, ref, watchEffect } from 'vue';
//hook
import { configHook } from './configHook'
import { requestHook } from './requestHook'
//components
import Pagination from '../pagination/Pagination.vue';
import SearchForm from '../search/index.vue'
import { useRouter } from "vue-router";
// store
import { useStore } from "vuex";

export default {
    name: "BasisTable",
    components: { Pagination, SearchForm },
    props: {
        columns: {
            type: Array,
            default: () => ([])
        },
        config: {
            type: Object,
            default: () => ({})
        },
        request: {
            type: Object,
            default: () => ({})
        },

    },
    emits: ["onload"],
    setup(props, { emit }) {
        // store
        // const store = useStore();
        // 获取实例上下文
        const { proxy } = getCurrentInstance();
        const { config, configInit } = configHook();
        const { requestData, table_data, handlerDeleteComfirm, saveDataId } = requestHook();
        const tableHeight = ref('');
        const data = reactive({
            table_data: [],
            render_header: props.columns,
            row_data_id: [],
            //currentPage: 1,
            //total: 0,

        })
        onBeforeMount(() => {
            //处理默认表格配置选项
            configInit(props.config);
            //请求数据
            getList(props.request)

            getTableList()
        })
        const getTableList = (data) => {
            table_data.data = data
        }

        //调用requestHook的requestData，请求列表数据
        const getList = (params, type) => {
            requestData(params, type).then(res => {
                emit("onload", table_data);
            });
        }
        /** 删除动作 */
        const handlerDelete = (type, val) => {
            console.log(val)
            if (type === "delete") { saveDataId(val); }
            handlerDeleteComfirm();
        }
        const multipleSelection = ref([]) // 多选的数据
        /** 复选框事件 */
        const handleSelectionChange = (val) => {
            //console.log("复选框")
            //console.log(val)
            saveDataId(val);
            multipleSelection.value = [];
            if (val.length > 0) {
                val.forEach(obj => {
                    multipleSelection.value.push(obj.projectid);
                })
            }
                    }


        const { push } = useRouter();
        /**跳转到新增项目页面 */
        const addInfo = () => {
            push({
                path: "/home/projectAdd"
            })
        }
        const getTableHeight = () => {
            let tableH = 200; //距离页面下方的高度
            let tableHeightDetil = window.innerHeight - tableH;
            if (tableHeightDetil <= 300) {
                tableHeight.value = 300;
            } else {
                tableHeight.value = window.innerHeight - tableH;
            }
        };
        watchEffect(() => {
            getTableHeight();
        });

        const expands = ref([])
        let expandColumn = (row, expandedRows) => {
            //row 被点击当前行的数据
            //expandedRows 存放页面中被展开行的数据 对应的数组就是 expand-row-keys

            //通过expandedRows长度来判断用户点击是展开还是折叠
            if (expandedRows.length) {
                //展开
                expands.value = []; //先干掉之前展开的行
                if (row) {
                    expands.value.push(row.projectid); //push新的行 (原理有点类似防抖)
                }
            } else {
                expands.value = []; //折叠 就清空expand-row-keys对应的数组
            }
        };

        let getRowKeys = (row) => {
            //row是当前行的数据
            //给每行绑定唯一的标识
            return row.projectid;
        };
        return {
            data,
            config,
            table_data,
            tableHeight,
            getTableList,
            requestData,
            getList,
            handlerDelete,
            handleSelectionChange,
            addInfo,
            multipleSelection,
            expandColumn,
            getRowKeys,
            expands,
           

        }
    }
}
</script>

<style scoped>
.margin-top-20 {
    margin-top: 20px;
}

.table-detail {
    margin: -2px 15px;
    background-color: lightgrey;
    border-radius: 5px;
    border-color: black;
    border-block: inherit;
}
</style>